package com.xiaozhen.jt809.service.impl;

import com.xiaozhen.common.redis.utils.RedisUtils;
import com.xiaozhen.jt809.domain.JT809MessageInfo;
import com.xiaozhen.jt809.handler.CommonHandlerFactory;
import com.xiaozhen.jt809.handler.MyHandler;
import com.xiaozhen.jt809.service.MsgHandleService;
import com.xiaozhen.jt809.utils.ByteArrayUtil;
import com.xiaozhen.jt809.utils.PacketUtil;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.InetSocketAddress;

/**
 * HISTORY
 *
 * @author zhenweisheng
 * @date 2021/9/16 14:19
 * @description:
 */
@Slf4j
@Service
public class MsgHandleServiceImpl implements MsgHandleService {

    @Autowired
    private CommonHandlerFactory handlerFactory;
    @Autowired
    private RedisUtils redisUtils;

    @Override
    public void handleMessage(String origin, ChannelHandlerContext ctx, Object msg) {
        JT809MessageInfo messageInfo = (JT809MessageInfo) msg;
        log.info(messageInfo.toString());
        //根据业务标识进行业务处理
        int msgId = messageInfo.getMessageHeader().getMsgId();
        byte[] msgIdBytes = ByteArrayUtil.int2bytes(msgId);
        log.info("业务类型ID：" + ByteArrayUtil.bytes2HexStr(ByteArrayUtil.subBytes(msgIdBytes, 2, 2)));
        MyHandler handler = handlerFactory.getHandler(msgId);
        if (handler != null) {
            handler.handler(ctx, messageInfo);
        } else {
            log.info("业务正在紧急添加中");
        }

    }

    @Override
    public JT809MessageInfo getMessageInfo(ChannelHandlerContext ctx, String message) {
        InetSocketAddress socketAddress = (InetSocketAddress) ctx.channel().remoteAddress();
        String hostAddress = socketAddress.getAddress().getHostAddress();
        int port = socketAddress.getPort();
        log.info("{},ip:{},port:{}", message, hostAddress, port);
        JT809MessageInfo messageInfo = redisUtils.get(hostAddress + ":" + port, JT809MessageInfo.class);
        //获取最新的报文序列号
        return messageInfo;
    }
}
